{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Considering the Environment\n",
    "\n",
    "In the previous chapters, we worked through \n",
    "a number of hands-on applications of machine learning,\n",
    "fitting models to a variety of datasets.\n",
    "And yet, we never stopped to contemplate\n",
    "either where data comes from in the first place\n",
    "or what we plan to ultimately *do* \n",
    "with the outputs from our models.\n",
    "Too often, machine learning developers\n",
    "in possession of data rush to develop models\n",
    "without pausing to consider these fundamental issues.\n",
    "\n",
    "Many failed machine learning deployments \n",
    "can be traced back to this pattern.\n",
    "Sometimes models appear to perform marvelously\n",
    "as measured by test set accuracy\n",
    "but fail catastrophically in deployment\n",
    "when the distribution of data suddenly shifts.\n",
    "More insidiously, sometimes the very deployment of a model\n",
    "can be the catalyst that perturbs the data distribution.\n",
    "Say, for example, that we trained a model \n",
    "to predict who will repay vs default on a loan,\n",
    "finding that an applicant's choice of footware \n",
    "was associated with the risk of default\n",
    "(Oxfords indicate repayment, sneakers indicate default).\n",
    "We might be inclined to thereafter grant loans\n",
    "to all applicants wearing Oxfords\n",
    "and to deny all applicants wearing sneakers.\n",
    "\n",
    "In this case, our ill-considered leap from \n",
    "pattern recognition to decision-making\n",
    "and our failure to critically consider the environment\n",
    "might have disastrous consequences.\n",
    "For starters, as soon as we began \n",
    "making decisions based on footware,\n",
    "customers would catch on and change their behavior.\n",
    "Before long, all applicants would be wearing Oxfords,\n",
    "without any coinciding improvement in credit-worthiness.\n",
    "Take a minute to digest this because similar issues abound\n",
    "in many applications of machine learning: \n",
    "by introducing our model-based decisions to the environment,\n",
    "we might break the model.\n",
    "\n",
    "While we cannot possibly give these topics \n",
    "a complete treatment in one section,\n",
    "we aim here to expose some common concerns,\n",
    "and to stimulate the critical thinking\n",
    "required to detect these situations early,\n",
    "mitigate damage, and use machine learning responsibly.\n",
    "Some of the solutions are simple\n",
    "(ask for the \"right\" data),\n",
    "some are technically difficult\n",
    "(implement a reinforcement learning system),\n",
    "and others require that we step outside the realm of\n",
    "statistical prediction altogether and \n",
    "grapple with difficult philosophical questions\n",
    "concerning the ethical application of algorithms.\n",
    "\n",
    "\n",
    "## Distribution Shift\n",
    "\n",
    "To begin, we stick with the passive predictions setting\n",
    "considering the various ways that data distributions might shift\n",
    "and what might be done to salvage model performance.\n",
    "In one classic setup, we assume that our training data\n",
    "was sampled from some distribution $p_S(\\mathbf{x},y)$\n",
    "but that our test data will consist \n",
    "of unlabeled examples drawn from \n",
    "some different distribution $p_T(\\mathbf{x},y)$.\n",
    "Already, we must confront a sobering reality.\n",
    "Absent any assumptions on how $p_S$ \n",
    "and $p_T$ relate to each other,\n",
    "learning a robust classifier is impossible.\n",
    "\n",
    "Consider a binary classification problem,\n",
    "where we wish to distinguish between dogs and cats.\n",
    "If the distribution can shift in arbitrary ways,\n",
    "then our setup permits the pathological case\n",
    "in which the distribution over inputs remains\n",
    "constant: $p_S(\\mathbf{x}) = p_T(\\mathbf{x})$\n",
    "but the labels are all flipped \n",
    "$p_S(y\\mid\\mathbf{x}) = 1 - p_T(y\\mid\\mathbf{x})$. \n",
    "In other words, if God can suddenly decide\n",
    "that in the future all \"cats\" are now dogs\n",
    "and what we previously called \"dogs\" are now cats---without\n",
    "any change in the distribution of inputs $p(\\mathbf{x})$,\n",
    "then we cannot possibly distinguish this setting \n",
    "from one in which the distribution did not change at all. \n",
    "\n",
    "Fortunately, under some restricted assumptions\n",
    "on the ways our data might change in the future,\n",
    "principled algorithms can detect shift \n",
    "and sometimes even adapt on the fly, \n",
    "improving on the accuracy of the original classifier.\n",
    "\n",
    "\n",
    "### Covariate Shift\n",
    "\n",
    "Among categories of distribution shift,\n",
    "*covariate shift* may be the most widely studied.\n",
    "Here, we assume that while the distribution of inputs \n",
    "may change over time, the labeling function, \n",
    "i.e., the conditional distribution \n",
    "$P(y \\mid \\mathbf{x})$ does not change.\n",
    "Statisticians call this *covariate shift*\n",
    "because the problem arises due to a \n",
    "a shift in the distribution of the *covariates* (the features).\n",
    "While we can sometimes reason about distribution shift\n",
    "without invoking causality, we note that covariate shift\n",
    "is the natural assumption to invoke in settings\n",
    "where we believe that $\\mathbf{x}$ causes $y$.\n",
    "\n",
    "Consider the challenge of distinguishing cats and dogs.\n",
    "Our training data might consist of images of the following kind:\n",
    "\n",
    "|cat|cat|dog|dog|\n",
    "|:---------------:|:---------------:|:---------------:|:---------------:|\n",
    "|<img src=\"https://github.com/d2l-ai/d2l-en/blob/master/img/cat3.jpg?raw=true\"/>|<img src=\"https://github.com/d2l-ai/d2l-en/blob/master/img/cat2.jpg?raw=true\"/>|<img src=\"https://github.com/d2l-ai/d2l-en/blob/master/img/dog1.jpg?raw=true\"/>|<img src=\"https://github.com/d2l-ai/d2l-en/blob/master/img/dog2.jpg?raw=true\"/>|\n",
    "\n",
    "At test time we are asked to classify the following images:\n",
    "\n",
    "|cat|cat|dog|dog|\n",
    "|:---------------:|:---------------:|:---------------:|:---------------:|\n",
    "|<img src=\"https://github.com/d2l-ai/d2l-en/blob/master/img/cat-cartoon1.png?raw=true\"/>|<img src=\"https://github.com/d2l-ai/d2l-en/blob/master/img/cat-cartoon2.png?raw=true\"/>|<img src=\"https://github.com/d2l-ai/d2l-en/blob/master/img/dog-cartoon1.png?raw=true\"/>|<img src=\"https://github.com/d2l-ai/d2l-en/blob/master/img/dog-cartoon2.png?raw=true\"/>|\n",
    "\n",
    "The training set consists of photos,\n",
    "while the test set contains only cartoons.\n",
    "Training on a dataset with substantially different\n",
    "characteristics from the test set\n",
    "can spell trouble absent a coherent plan \n",
    "for how to adapt to the new domain.\n",
    "\n",
    "\n",
    "### Label Shift\n",
    " \n",
    "*Label shift* describes the converse problem.\n",
    "Here, we assume that the label marginal $P(y)$\n",
    "can change (inducing a change in $P(\\mathbf{x})$)\n",
    "but the class-conditional distribution \n",
    "$P(\\mathbf{x} \\mid y)$ remains fixed across domains.\n",
    "Label shift is a reasonable assumption to make\n",
    "when we believe that $y$ causes $\\mathbf{x}$.\n",
    "For example, we may want to predict diagnoses \n",
    "given their symptoms (or other manifestations),\n",
    "even as the relative prevalence of diagnoses \n",
    "are changing over time.\n",
    "Label shift is the appropriate assumption here\n",
    "because diseases cause symptoms.\n",
    "In some degenerate cases the label shift \n",
    "and covariate shift assumptions can hold simultaneously.\n",
    "For example, when the label is deterministic,\n",
    "the covariate shift assumption will be satisfied,\n",
    "even when $y$ causes $\\mathbf{x}$.\n",
    "Interestingly, in these cases,\n",
    "it is often advantageous to work with methods\n",
    "that flow from the label shift assumption.\n",
    "That is because these methods tend \n",
    "to involve manipulating objects that look like the label\n",
    "(which is often low-dimensional),\n",
    "as opposed to objects that look like the input,\n",
    "which (in deep learning) tends to be high-dimensional.\n",
    "\n",
    "\n",
    "\n",
    "### Concept Shift\n",
    "\n",
    "We may also encounter the related problem of *concept shift*,\n",
    "which arises when the very definitions of labels can change.\n",
    "This sounds weird---a *cat* is a *cat*, no?\n",
    "However, other categories are subject to changes in usage over time.\n",
    "Diagnostic criteria for mental illness,\n",
    "what passes for fashionable, and job titles,\n",
    "are all subject to considerable \n",
    "amounts of *concept shift*.\n",
    "It turns out that if we navigate around the United States,\n",
    "shifting the source of our data by geography,\n",
    "we will find considerable concept shift regarding\n",
    "the distribution of names for *soft drinks*\n",
    "as shown in :numref:`fig_popvssoda`.\n",
    "\n",
    "<img src=\"https://github.com/d2l-ai/d2l-en/blob/master/img/popvssoda.png?raw=true\" alt=\"Drawing\" style=\"width: 400px;\"/>\n",
    "\n",
    "If we were to build a machine translation system,\n",
    "the distribution $P(y \\mid x)$ might be different\n",
    "depending on our location.\n",
    "This problem can be tricky to spot.\n",
    "We might hope to exploit knowledge\n",
    "that shift only takes place gradually\n",
    "(either in a temporal or geographic sense).\n",
    "\n",
    "\n",
    "\n",
    "### Examples\n",
    "\n",
    "Before delving into formalism and algorithms,\n",
    "we can discuss some concrete situations\n",
    "where covariate or concept shift might not be obvious.\n",
    "\n",
    "\n",
    "#### Medical Diagnostics\n",
    "\n",
    "Imagine that you want to design an algorithm to detect cancer.\n",
    "You collect data from healthy and sick people\n",
    "and you train your algorithm.\n",
    "It works fine, giving you high accuracy\n",
    "and you conclude that you’re ready\n",
    "for a successful career in medical diagnostics.\n",
    "*Not so fast.*\n",
    "\n",
    "The distributions that gave rise to the training data\n",
    "and those you will encounter in the wild might differ considerably.\n",
    "This happened to an unfortunate startup\n",
    "that one of us worked with years ago.\n",
    "They were developing a blood test for a disease\n",
    "that predominantly affects older men \n",
    "and hoped to study it using blood samples\n",
    "that they had collected from patients.\n",
    "However, it is considerably more difficult\n",
    "to obtain blood samples from healthy men \n",
    "than sick patients already in the system.\n",
    "To compensate, the startup solicited\n",
    "blood donations from students on a university campus\n",
    "to serve as healthy controls in developing their test.\n",
    "Then they asked whether we could help them\n",
    "to build a classifier for detecting the disease.\n",
    "\n",
    "As we explained to them,\n",
    "it would indeed be easy to distinguish\n",
    "between the healthy and sick cohorts\n",
    "with near-perfect accuracy.\n",
    "However, that's because the test subjects \n",
    "differed in age, hormone levels,\n",
    "physical activity, diet, alcohol consumption,\n",
    "and many more factors unrelated to the disease.\n",
    "This was unlikely to be the case with real patients.\n",
    "Due to their sampling procedure,\n",
    "we could expect to encounter extreme covariate shift. \n",
    "Moreover, this case was unlikely to be\n",
    "correctable via conventional methods.\n",
    "In short, they wasted a significant sum of money.\n",
    "\n",
    "#### Self Driving Cars\n",
    "\n",
    "Say a company wanted to leverage machine learning\n",
    "for developing self-driving cars.\n",
    "One key component here is a roadside detector.\n",
    "Since real annotated data is expensive to get,\n",
    "they had the (smart and questionable) idea\n",
    "to use synthetic data from a game rendering engine\n",
    "as additional training data.\n",
    "This worked really well on \"test data\" \n",
    "drawn from the rendering engine.\n",
    "Alas, inside a real car it was a disaster.\n",
    "As it turned out, the roadside had been rendered\n",
    "with a very simplistic texture.\n",
    "More importantly, *all* the roadside had been rendered\n",
    "with the *same* texture and the roadside detector\n",
    "learned about this \"feature\" very quickly.\n",
    "\n",
    "A similar thing happened to the US Army\n",
    "when they first tried to detect tanks in the forest.\n",
    "They took aerial photographs of the forest without tanks,\n",
    "then drove the tanks into the forest\n",
    "and took another set of pictures.\n",
    "The classifier appeared to work *perfectly*.\n",
    "Unfortunately, it had merely learned\n",
    "how to distinguish trees with shadows\n",
    "from trees without shadows---the first set\n",
    "of pictures was taken in the early morning,\n",
    "the second one at noon.\n",
    "\n",
    "#### Nonstationary distributions\n",
    "\n",
    "A much more subtle situation arises\n",
    "when the distribution changes slowly\n",
    "and the model is not updated adequately.\n",
    "Here are some typical cases:\n",
    "\n",
    "* We train a computational advertising model and then fail to update it frequently (e.g., we forget to incorporate that an obscure new device called an iPad was just launched).\n",
    "* We build a spam filter. It works well at detecting all spam that we have seen so far. But then the spammers wisen up and craft new messages that look unlike anything we have seen before.\n",
    "* We build a product recommendation system. It works throughout the winter but then continues to recommend Santa hats long after Christmas.\n",
    "\n",
    "#### More Anecdotes\n",
    "\n",
    "* We build a face detector. It works well on all benchmarks. Unfortunately it fails on test data---the offending examples are close-ups where the face fills the entire image (no such data was in the training set).\n",
    "* We build a web search engine for the USA market and want to deploy it in the UK.\n",
    "* We train an image classifier by compiling a large dataset where each among a large set of classes is equally represented in the dataset, say 1000 categories, represented by 1000 images each. Then we deploy the system in the real world, where the actual label distribution of photographs is decidedly non-uniform.\n",
    "\n",
    "In short, there are many cases \n",
    "where training and test distributions\n",
    "$p(\\mathbf{x}, y)$ are different.\n",
    "In some cases, we get lucky and the models work\n",
    "despite covariate, label, or concept shift.\n",
    "In other cases, we can do better by employing\n",
    "principled strategies to cope with the shift.\n",
    "The remainder of this section grows considerably more technical.\n",
    "The impatient reader could continue on to the next section\n",
    "as this material is not prerequisite to subsequent concepts.\n",
    "\n",
    "### Covariate Shift Correction\n",
    "\n",
    "Assume that we want to estimate \n",
    "some dependency $P(y \\mid \\mathbf{x})$\n",
    "for which we have labeled data $(\\mathbf{x}_i, y_i)$.\n",
    "Unfortunately, the observations $x_i$ are drawn\n",
    "from some *target* distribution $q(\\mathbf{x})$\n",
    "rather than the *source* distribution $p(\\mathbf{x})$.\n",
    "To make progress, we need to reflect about what exactly\n",
    "is happening during training:\n",
    "we iterate over training data and associated labels\n",
    "$\\{(\\mathbf{x}_1, y_1), \\ldots, (\\mathbf{x}_n, y_n)\\}$\n",
    "and update the weight vectors of the model after every minibatch.\n",
    "We sometimes additionally apply some penalty to the parameters,\n",
    "using weight decay, dropout, or some other related technique.\n",
    "This means that we largely minimize the loss on the training.\n",
    "\n",
    "$$\n",
    "\\mathop{\\mathrm{minimize}}_w \\frac{1}{n} \\sum_{i=1}^n l(x_i, y_i, f(x_i)) + \\mathrm{some~penalty}(w).\n",
    "$$\n",
    "\n",
    "Statisticians call the first term an *empirical average*,\n",
    "i.e., an average computed over the data drawn from $P(x) P(y \\mid x)$.\n",
    "If the data is drawn from the \"wrong\" distribution $q$,\n",
    "we can correct for that by using the following simple identity:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\int p(\\mathbf{x}) f(\\mathbf{x}) dx \n",
    "& = \\int q(\\mathbf{x}) f(\\mathbf{x}) \\frac{p(\\mathbf{x})}{q(\\mathbf{x})} dx.\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "In other words, we need to re-weight each instance\n",
    "by the ratio of probabilities\n",
    "that it would have been drawn from the correct distribution\n",
    "$\\beta(\\mathbf{x}) := p(\\mathbf{x})/q(\\mathbf{x})$.\n",
    "Alas, we do not know that ratio,\n",
    "so before we can do anything useful we need to estimate it.\n",
    "Many methods are available,\n",
    "including some fancy operator-theoretic approaches\n",
    "that attempt to recalibrate the expectation operator directly\n",
    "using a minimum-norm or a maximum entropy principle.\n",
    "Note that for any such approach, we need samples\n",
    "drawn from both distributions---the \"true\" $p$, e.g.,\n",
    "by access to training data, and the one used\n",
    "for generating the training set $q$ (the latter is trivially available).\n",
    "Note however, that we only need samples $\\mathbf{x} \\sim q(\\mathbf{x})$;\n",
    "we do not to access labels $y \\sim q(y)$.\n",
    "\n",
    "In this case, there exists a very effective approach\n",
    "that will give almost as good results: logistic regression.\n",
    "This is all that is needed to compute estimate probability ratios.\n",
    "We learn a classifier to distinguish \n",
    "between data drawn from $p(\\mathbf{x})$\n",
    "and data drawn from $q(\\mathbf{x})$.\n",
    "If it is impossible to distinguish \n",
    "between the two distributions\n",
    "then it means that the associated instances \n",
    "are equally likely to come from \n",
    "either one of the two distributions.\n",
    "On the other hand, any instances \n",
    "that can be well discriminated\n",
    "should be significantly overweighted \n",
    "or underweighted accordingly.\n",
    "For simplicity’s sake assume that we have \n",
    "an equal number of instances from both distributions, \n",
    "denoted by $\\mathbf{x}_i \\sim p(\\mathbf{x})$ \n",
    "and $\\mathbf{x}_i' \\sim q(\\mathbf{x})$, respectively.\n",
    "Now denote by $z_i$ labels that are 1\n",
    "for data drawn from $p$ and -1 for data drawn from $q$.\n",
    "Then the probability in a mixed dataset is given by\n",
    "\n",
    "$$P(z=1 \\mid \\mathbf{x}) = \\frac{p(\\mathbf{x})}{p(\\mathbf{x})+q(\\mathbf{x})} \\text{ and hence } \\frac{P(z=1 \\mid \\mathbf{x})}{P(z=-1 \\mid \\mathbf{x})} = \\frac{p(\\mathbf{x})}{q(\\mathbf{x})}.$$\n",
    "\n",
    "Hence, if we use a logistic regression approach,\n",
    "where $P(z=1 \\mid \\mathbf{x})=\\frac{1}{1+\\exp(-f(\\mathbf{x}))}$.\n",
    "it follows that\n",
    "\n",
    "$$\n",
    "\\beta(\\mathbf{x}) = \\frac{1/(1 + \\exp(-f(\\mathbf{x})))}{\\exp(-f(\\mathbf{x}))/(1 + \\exp(-f(\\mathbf{x})))} = \\exp(f(\\mathbf{x})).\n",
    "$$\n",
    "\n",
    "As a result, we need to solve two problems:\n",
    "first one to distinguish between\n",
    "data drawn from both distributions,\n",
    "and then a reweighted minimization problem\n",
    "where we weigh terms by $\\beta$, e.g., via the head gradients.\n",
    "Here's a prototypical algorithm for that purpose\n",
    "which uses an unlabeled training set $X$ and test set $Z$:\n",
    "\n",
    "1. Generate training set with $\\{(\\mathbf{x}_i, -1) ... (\\mathbf{z}_j, 1)\\}$.\n",
    "1. Train binary classifier using logistic regression to get function $f$.\n",
    "1. Weigh training data using $\\beta_i = \\exp(f(\\mathbf{x}_i))$ or better $\\beta_i = \\min(\\exp(f(\\mathbf{x}_i)), c)$.\n",
    "1. Use weights $\\beta_i$ for training on $X$ with labels $Y$.\n",
    "\n",
    "Note that this method relies on a crucial assumption.\n",
    "For this scheme to work, we need that each data point\n",
    "in the target (test time) distribution\n",
    "had nonzero probability of occurring at training time.\n",
    "If we find a point where $q(\\mathbf{x}) > 0$ but $p(\\mathbf{x}) = 0$,\n",
    "then the corresponding importance weight should be infinity.\n",
    "\n",
    "*Generative Adversarial Networks*\n",
    "use a very similar idea to that described above\n",
    "to engineer a *data generator* that outputs data\n",
    "that cannot be distinguished\n",
    "from examples sampled from a reference dataset.\n",
    "In these approaches, we use one network, $f$\n",
    "to distinguish real versus fake data\n",
    "and a second network $g$ that tries \n",
    "to fool the discriminator $f$\n",
    "into accepting fake data as real.\n",
    "We will discuss this in much more detail later.\n",
    "\n",
    "\n",
    "### Label Shift Correction\n",
    "\n",
    "Assume that we are dealing with a \n",
    "$k$-way multiclass classification task.\n",
    "When the distribution of labels shifts over time,\n",
    "$p(y) \\neq q(y)$ but the class-conditional distributions \n",
    "stay the same $p(\\mathbf{x})=q(\\mathbf{x})$.\n",
    "Here, our importance weights will correspond to the\n",
    "label likelihood ratios $q(y)/p(y)$.\n",
    "One nice thing about label shift is that\n",
    "if we have a reasonably good model \n",
    "(on the source distribution)\n",
    "then we can get consistent estimates of these weights\n",
    "without ever having to deal with the ambient dimension\n",
    "In deep learning, the inputs tend \n",
    "to be high-dimensional objects like images,\n",
    "while the labels are often simpler objects like categories.\n",
    "\n",
    "To estimate the target label distribution,\n",
    "we first take our reasonably good off the shelf classifier\n",
    "(typically trained on the training data)\n",
    "and compute its confusion matrix using the validation set\n",
    "(also from the training distribution).\n",
    "The confusion matrix, C, is simply a $k \\times k$ matrix,\n",
    "where each column corresponds to the *actual* label\n",
    "and each row corresponds to our model's predicted label.\n",
    "Each cell's value $c_{ij}$ is the fraction of predictions\n",
    "where the true label was $j$ *and* our model predicted $i$.\n",
    "\n",
    "Now, we cannot calculate the confusion matrix\n",
    "on the target data directly,\n",
    "because we do not get to see the labels for the examples\n",
    "that we see in the wild,\n",
    "unless we invest in a complex real-time annotation pipeline.\n",
    "What we can do, however, is average all of our models predictions\n",
    "at test time together, yielding the mean model output $\\mu_y$.\n",
    "\n",
    "It turns out that under some mild conditions---if \n",
    "our classifier was reasonably accurate in the first place,\n",
    "and if the target data contains only classes of images \n",
    "that we have seen before,\n",
    "and if the label shift assumption holds in the first place\n",
    "(the strongest assumption here),\n",
    "then we can recover the test set label distribution\n",
    "by solving a simple linear system $C \\cdot q(y) = \\mu_y$.\n",
    "If our classifier is sufficiently accurate to begin with,\n",
    "then the confusion $C$ will be invertible,\n",
    "and we get a solution $q(y) = C^{-1} \\mu_y$.\n",
    "Here we abuse notation a bit, using $q(y)$\n",
    "to denote the vector of label frequencies.\n",
    "Because we observe the labels on the source data,\n",
    "it is easy to estimate the distribution $p(y)$.\n",
    "Then for any training example $i$ with label $y$,\n",
    "we can take the ratio of our estimates $\\hat{q}(y)/\\hat{p}(y)$\n",
    "to calculate the weight $w_i$,\n",
    "and plug this into the weighted risk minimization algorithm above.\n",
    "\n",
    "\n",
    "### Concept Shift Correction\n",
    "\n",
    "Concept shift is much harder to fix in a principled manner.\n",
    "For instance, in a situation where suddenly the problem changes\n",
    "from distinguishing cats from dogs to one of\n",
    "distinguishing white from black animals,\n",
    "it will be unreasonable to assume\n",
    "that we can do much better than just collecting new labels\n",
    "and training from scratch.\n",
    "Fortunately, in practice, such extreme shifts are rare.\n",
    "Instead, what usually happens is that the task keeps on changing slowly.\n",
    "To make things more concrete, here are some examples:\n",
    "\n",
    "* In computational advertising, new products are launched, \n",
    "old products become less popular. This means that the distribution over ads and their popularity changes gradually and any click-through rate predictor needs to change gradually with it.\n",
    "* Traffic camera lenses degrade gradually due to environmental wear, affecting image quality progressively.\n",
    "* News content changes gradually (i.e., most of the news remains unchanged but new stories appear).\n",
    "\n",
    "In such cases, we can use the same approach that we used for training networks to make them adapt to the change in the data. In other words, we use the existing network weights and simply perform a few update steps with the new data rather than training from scratch.\n",
    "\n",
    "## A Taxonomy of Learning Problems\n",
    "\n",
    "Armed with knowledge about how to deal with changes in $p(x)$ and in $P(y \\mid x)$, we can now consider some other aspects of machine learning problem formulation.\n",
    "\n",
    "\n",
    "* **Batch Learning.** Here we have access to training data and labels $\\{(x_1, y_1), \\ldots, (x_n, y_n)\\}$, which we use to train a network $f(x, w)$. Later on, we deploy this network to score new data $(x, y)$ drawn from the same distribution. This is the default assumption for any of the problems that we discuss here. For instance, we might train a cat detector based on lots of pictures of cats and dogs. Once we trained it, we ship it as part of a smart catdoor computer vision system that lets only cats in. This is then installed in a customer's home and is never updated again (barring extreme circumstances).\n",
    "* **Online Learning.** Now imagine that the data $(x_i, y_i)$ arrives one sample at a time. More specifically, assume that we first observe $x_i$, then we need to come up with an estimate $f(x_i, w)$ and only once we have done this, we observe $y_i$ and with it, we receive a reward (or incur a loss), given our decision. Many real problems fall into this category. E.g., we need to predict tomorrow's stock price, this allows us to trade based on that estimate and at the end of the day we find out whether our estimate allowed us to make a profit. In other words, we have the following cycle where we are continuously improving our model given new observations.\n",
    "\n",
    "$$\n",
    "\\mathrm{model} ~ f_t \\longrightarrow\n",
    "\\mathrm{data} ~ x_t \\longrightarrow\n",
    "\\mathrm{estimate} ~ f_t(x_t) \\longrightarrow\n",
    "\\mathrm{observation} ~ y_t \\longrightarrow\n",
    "\\mathrm{loss} ~ l(y_t, f_t(x_t)) \\longrightarrow\n",
    "\\mathrm{model} ~ f_{t+1}\n",
    "$$\n",
    "\n",
    "* **Bandits.** They are a *special case* of the problem above. While in most learning problems we have a continuously parametrized function $f$ where we want to learn its parameters (e.g., a deep network), in a bandit problem we only have a finite number of arms that we can pull (i.e., a finite number of actions that we can take). It is not very surprising that for this simpler problem stronger theoretical guarantees in terms of optimality can be obtained. We list it mainly since this problem is often (confusingly) treated as if it were a distinct learning setting.\n",
    "* **Control (and nonadversarial Reinforcement Learning).** In many cases the environment remembers what we did. Not necessarily in an adversarial manner but it will just remember and the response will depend on what happened before. E.g., a coffee boiler controller will observe different temperatures depending on whether it was heating the boiler previously. PID (proportional integral derivative) controller algorithms are a popular choice there. Likewise, a user's behavior on a news site will depend on what we showed him previously (e.g., he will read most news only once). Many such algorithms form a model of the environment in which they act such as to make their decisions appear less random (i.e., to reduce variance).\n",
    "* **Reinforcement Learning.** In the more general case of an environment with memory, we may encounter situations where the environment is trying to *cooperate* with us (cooperative games, in particular for non-zero-sum games), or others where the environment will try to *win*. Chess, Go, Backgammon or StarCraft are some of the cases. Likewise, we might want to build a good controller for autonomous cars. The other cars are likely to respond to the autonomous car's driving style in nontrivial ways, e.g., trying to avoid it, trying to cause an accident, trying to cooperate with it, etc.\n",
    "\n",
    "One key distinction between the different situations above is that the same strategy that might have worked throughout in the case of a stationary environment, might not work throughout when the environment can adapt. For instance, an arbitrage opportunity discovered by a trader is likely to disappear once he starts exploiting it. The speed and manner at which the environment changes determines to a large extent the type of algorithms that we can bring to bear. For instance, if we *know* that things may only change slowly, we can force any estimate to change only slowly, too. If we know that the environment might change instantaneously, but only very infrequently, we can make allowances for that. These types of knowledge are crucial for the aspiring data scientist to deal with concept shift, i.e., when the problem that he is trying to solve changes over time.\n",
    "\n",
    "\n",
    "## Fairness, Accountability, and Transparency in Machine Learning\n",
    "\n",
    "Finally, it is important to remember\n",
    "that when you deploy machine learning systems\n",
    "you are not merely optimizing a predictive model---you \n",
    "are typically providing a tool that will\n",
    "be used to (partially or fully) automate decisions.\n",
    "These technical systems can impact the lives\n",
    "of individuals subject to the resulting decisions.\n",
    "The leap from considering predictions to decisions\n",
    "raises not only new technical questions,\n",
    "but also a slew of ethical questions \n",
    "that must be carefully considered.\n",
    "If we are deploying a medical diagnostic system,\n",
    "we need to know for which populations \n",
    "it may work and which it may not.\n",
    "Overlooking foreseeable risks to the welfare of \n",
    "a subpopulation could cause us to administer inferior care.\n",
    "Moreover, once we contemplate decision-making systems,\n",
    "we must step back and reconsider how we evaluate our technology.\n",
    "Among other consequences of this change of scope,\n",
    "we will find that *accuracy* is seldom the right metric.\n",
    "For instance, when translating predictions into actions,\n",
    "we will often want to take into account \n",
    "the potential cost sensitivity of erring in various ways.\n",
    "If one way of misclassifying an image \n",
    "could be perceived as a racial sleight,\n",
    "while misclassification to a different category\n",
    "would be harmless, then we might want to adjust \n",
    "our thresholds accordingly, accounting for societal values\n",
    "in designing the decision-making protocol.\n",
    "We also want to be careful about \n",
    "how prediction systems can lead to feedback loops.\n",
    "For example, consider predictive policing systems,\n",
    "which allocate patrol officers \n",
    "to areas with high forecasted crime.\n",
    "It is easy to see how a worrying pattern can emerge:\n",
    "\n",
    " 1. Neighborhoods with more crime get more patrols. \n",
    " 1. Consequently, more crimes are discovered in these neighborhoods, entering the training data available for future iterations.\n",
    " 1. Exposed to more positives, the model predicts yet more crime in these neighborhoods.\n",
    " 1. In the next iteration, the updated model targets the same neighborhood even more heavily leading to yet more crimes discovered, etc.\n",
    "\n",
    "Often, the various mechanisms by which \n",
    "a model's predictions become coupled to its training data \n",
    "are unaccounted for in the modeling process. \n",
    "This can lead to what researchers call \"runaway feedback loops.\" \n",
    "Additionally, we want to be careful about \n",
    "whether we are addressing the right problem in the first place. \n",
    "Predictive algorithms now play an outsize role \n",
    "in mediating the dissemination of information.\n",
    "Should the news that an individual encounters\n",
    "be determined by the set of Facebook pages they have *Liked*? \n",
    "These are just a few among the many pressing ethical dilemmas\n",
    "that you might encounter in a career in machine learning.\n",
    "\n",
    "\n",
    "\n",
    "## Summary\n",
    "\n",
    "* In many cases training and test sets do not come from the same distribution. This is called covariate shift.\n",
    "* Under the corresponding assumptions, *covariate* and *label* shift can be detected and corrected for at test time. Failure to account for this bias can become problematic at test time.\n",
    "* In some cases, the environment may *remember* automated actions and respond in surprising ways. We must account for this possibility when building models and continue to monitor live systems, open to the possibility that our models and the environment will become entangled in unanticipated ways.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. What could happen when we change the behavior of a search engine? What might the users do? What about the advertisers?\n",
    "1. Implement a covariate shift detector. Hint: build a classifier.\n",
    "1. Implement a covariate shift corrector.\n",
    "1. What could go wrong if training and test sets are very different? What would happen to the sample weights?\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
